package com.yf.system.modules.login.cropchat;


import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yf.ability.login.cropwechat.config.CropWechatConfig;
import com.yf.ability.login.cropwechat.dto.response.DetailRespDTO;
import com.yf.ability.login.cropwechat.service.CropWechatLoginService;
import com.yf.ability.login.wechat.dto.response.WxUrlRespDTO;
import com.yf.ability.shiro.dto.SysUserLoginDTO;
import com.yf.base.api.api.ApiRest;
import com.yf.base.api.api.controller.BaseController;
import com.yf.system.modules.user.UserUtils;
import com.yf.system.modules.user.enums.LoginType;
import com.yf.system.modules.user.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 微信登录后台处理类
 * @author bool
 */
@Log4j2
@Api(tags = {"企业微信登录"})
@RestController
public class CropWxLoginController extends BaseController {

    @Autowired
    private CropWechatLoginService cropWechatLoginService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private CropWechatConfig cropWechatConfig;

    /**
     * 网页授权链接地址
     */
    private final static String OAUTH_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={cropId}&redirect_uri={redirect}&response_type=code&scope=snsapi_privateinfo&state={state}&agentid={agentId}#wechat_redirect";

    /**
     * 扫码授权登录地址
     */
    private final static String LOGIN_URL = "https://open.work.weixin.qq.com/wwopen/sso/qrConnect?appid={cropId}&agentid={agentId}&redirect_uri={redirect}&state={state}";


    /**
     * 获取企业微信扫码登录地址
     * @return
     */
    @PostMapping("/api/common/crop-wechat/get-url")
    @ApiOperation(value = "获取企业微信扫码登录地址", notes = "适应PC场景")
    public ApiRest<WxUrlRespDTO> getUrl() {

        // state为登录跳转标识，可以跳转到h5页面
        String url = LOGIN_URL
                .replace("{cropId}", cropWechatConfig.getCropId())
                .replace("{agentId}", cropWechatConfig.getAgentId())
                // 统一跳转地址
                .replace("{redirect}", cropWechatConfig.getRedirect())
                // 扫码肯定是PC端的
                .replace("{state}", "pc");

        WxUrlRespDTO respDTO = new WxUrlRespDTO();
        respDTO.setUrl(url);
        return success(respDTO);
    }

    /**
     * 登录后跳转到页面同步会话
     * @param code
     * @return
     * @throws IOException
     */
    @GetMapping("/api/common/crop-wechat/redirect")
    @ApiOperation(value = "企业微信登录回调", notes = "适应PC场景")
    public ModelAndView webRedirect(@RequestParam("code") String code) {
        // 获取会话
        DetailRespDTO resp = cropWechatLoginService.webLogin(
                cropWechatConfig.getCropId(),
                cropWechatConfig.getCropSecret(),
                code);

        // 登录并返回
        SysUserLoginDTO loginDTO = sysUserService.loginByThird(LoginType.CROP_WECHAT, resp.getUserid(), resp.getName(), resp.getAvatar());

        ModelAndView mv = new ModelAndView("sync");
        mv.addObject("token", loginDTO.getToken());
        mv.addObject("sec", 2);
        mv.addObject("callback", "/");
        return mv;
    }

    /**
     * 在企业微信的浏览器里面，点击URL直接进行同步登录
     * 注意：企业微信PC端没有内嵌浏览器，所以此链接一般放在H5中
     * @return
     */
    @GetMapping( "/api/connect/cwx")
    @ApiOperation(value = "企业微信同步跳转地址", notes = "直接将此URL嵌入到企业微信的工作台里面，需要管理员在微信后台创建应用")
    public void connect(HttpServletResponse response) throws IOException {

        // 如果登录，直接去首页
        if(UserUtils.isLogin()){
            response.sendRedirect("/");
            return;
        }

        // state为登录跳转标识，可以跳转到h5页面
        String url = OAUTH_URL
                .replace("{cropId}", cropWechatConfig.getCropId())
                .replace("{agentId}", cropWechatConfig.getAgentId())
                // 统一跳转地址
                .replace("{redirect}", cropWechatConfig.getRedirect())
                // 目前场景是手机端
                .replace("{state}", "h5_"+IdWorker.getIdStr());

        response.sendRedirect(url);
    }
}
